#pragma once
#include <iostream>
#include <poll.h>
#include "Socket.hpp"
#define NUM sizeof(fd_set) * 8
using namespace SocketModule;
using namespace LogMudule;

const int gdefaultfd = -1;
#define MAX 4096
class PollServer
{
public:
    PollServer(uint16_t port)
        : _socket(std::make_unique<TcpSocket>()),
          _isrunning(false),
          _port(port)
    {
    }
    ~PollServer()
    {
    }
    void Init()
    {
        _socket->BuildTcpSocket(_port);
        for (int i = 0; i < MAX; i++)
        {
            _pfds[i].fd = gdefaultfd;
            _pfds[i].events = 0;
            _pfds[i].revents = 0;
        }
        _pfds[0].fd = _socket->Fd();
        _pfds[0].events |= POLLIN;
    }
    std::string Events2Str(short events)
    {
        std::string s = ((events & POLLIN) ? "EPOLLIN" : "");
        s += ((events & POLLOUT) ? "POLLOUT" : "");
        return s;
    }
    void TestFd()
    {
        std::cout << "pollfd: ";
        for (int i = 0; i < MAX; i++)
        {
            if (_pfds[i].fd == gdefaultfd)
                continue;
            std::cout << _pfds[i].fd << "[" << Events2Str(_pfds[i].events) << "] ";
        }
        std::cout << "\n";
    }
    void Start()
    {
        int timeout = 2000;
        _isrunning = true;
        while (true)
        {
            int n = poll(_pfds, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out" << std::endl;
                break;
            case -1:
                perror("poll");
                break;
            default:
                std::cout << "已有用户准备就绪" << std::endl;
                Dispatcher();
                TestFd();
                break;
            }
        }
    }
    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_pfds[i].fd == gdefaultfd)
                continue;
            // 判断是否在rfds集合中
            if (_pfds[i].fd == _socket->Fd())
            {
                if (_pfds[i].events & POLLIN)
                    Accpetor();
            }
            else
            {
                if (_pfds[i].events & POLLIN)
                    Recver(i);
            }
        }
    }
    void Recver(int who)
    {
        char buffer[1024];
        int n = recv(_pfds[who].fd, buffer, sizeof(buffer) - 1, 0);
        LOG(LogLevel::DEBUG)<<"+++++++++++++++++++++++++++++";
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "cilent: #" << buffer << std::endl;
            std::string message;
            message += "Echo #";
            message += buffer;
            send(_pfds[who].fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "客户端退出 ：" << _pfds[who].fd;
            close(_pfds[who].fd);
            _pfds[who].fd = gdefaultfd;
            _pfds[who].events = _pfds[who].revents = 0;
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << _pfds[who].fd;
            close(_pfds[who].fd);
            _pfds[who].fd = gdefaultfd;
            _pfds[who].events = _pfds[who].revents = 0;
        }
    }
    void Accpetor()
    {
        InetAddr client;
        int newfd = _socket->Accept(&client);
        if (newfd < 0)
            return;
        // 加入托管
        else
        {
            std::cout << "获得了一个新的链接: " << newfd << " client info: " << client.Addr() << std::endl;
            int pos = -1;
            for (int i = 0; i < MAX; i++)
            {
                if (_pfds[i].fd == gdefaultfd)
                {
                    pos = i;
                    break;
                }
            }
            if (pos == -1)
            {
                std::cout << "服务器已满........" << std::endl;
                close(newfd);
            }
            else
            {
                _pfds[pos].fd = newfd;
                _pfds[pos].events = POLLIN;
            }
        }
    }

private:
    std::unique_ptr<Socket> _socket;
    bool _isrunning;
    u_int16_t _port;
    struct pollfd _pfds[MAX];
};
